<?php
namespace backend\modules\orders\lib;
/**
 *
 * 快递鸟电子面单接口
 *
 * @技术QQ群: 340378554
 * @see: http://kdniao.com/api-eorder
 * @copyright: 深圳市快金数据技术服务有限公司
 * 
 * ID和Key请到官网申请：http://kdniao.com/reg
 *
 * Class KdApiEOrderDemo
 * @package backend\modules\orders\lib\KdApiEOrderDemo
 */

class KdApiEOrderDemo{
    public static $EBusinessID;
    public static $AppKey;
    public static $ReqURL;

    public function __construct()
    {
        $this->_setEBusinessID();
        $this->_setAppKey();
        $this->_setReqURL();
    }

    public function _setEBusinessID()
    {
        self::$EBusinessID='1301720';
    }

    public function _setAppKey()
    {
        self::$AppKey='e82f0f2f-cccd-4e2f-8e21-203580b34605';
    }

    public function _setReqURL()
    {
        self::$ReqURL='http://testapi.kdniao.cc:8081/api/EOrderService';
    }

    function setTempInfoShip($order_info){
        //构造电子面单提交信息
        $eorder = array();
        $eorder["ShipperCode"] = "SF";
        $eorder["OrderCode"] = $order_info['order_sn'];
        $eorder["PayType"] = 4;
        $eorder["ExpType"] = 1;

        $sender =  array();
        $sender["Name"] = "小普未来科技(深圳)公司";
        $sender["Mobile"] = "13760447005";
        $sender["ProvinceName"] = "广东省";
        $sender["CityName"] = "深圳市";
        $sender["ExpAreaName"] = "南山区";
        $sender["Address"] = "德赛大厦903A";

        $receiver = array();
        $receiver["Name"] = $order_info["consignee"];
        $receiver["Mobile"] = $order_info["tel"];
        $receiver["ProvinceName"] = $order_info["province_name"];
        $receiver["CityName"] = $order_info['city_name'] ;
        $receiver["ExpAreaName"] = $order_info['district_name'] ;
        $receiver["Address"] =$order_info['address'] ;

        $commodityOne =  array();
        $commodityOne["GoodsName"] = "其他";
        $commodity =  array();
        $commodity[] = $commodityOne;

        $eorder["Sender"] = $sender;
        $eorder["Receiver"] = $receiver;
        $eorder["Commodity"] = $commodity;
        $eorder["IsReturnPrintTemplate"] = 1;
        $eorder["IsNotice"] = 0;


//调用电子面单
        $jsonParam = json_encode($eorder);

//$jsonParam = JSON($eorder);//兼容php5.2（含）以下

//echo "电子面单接口提交内容：<br/>".$jsonParam;
        $jsonResult = $this->submitEOrder($jsonParam);
//echo "<br/><br/>电子面单提交结果:<br/>".$jsonResult;

//解析电子面单返回结果
        $result = json_decode($jsonResult, true);
//echo "<br/><br/>返回码:".$result["ResultCode"];
        if($result["ResultCode"] == "100") {
            return $result;
        }else{
            print_r($result);exit;
        }
    }

//-------------------------------------------------------------


    /**
     * Json方式 调用电子面单接口
     */
    public function submitEOrder($requestData){
        $datas = array(
            'EBusinessID' => static::$EBusinessID,
            'RequestType' => '1007',
            'RequestData' => urlencode($requestData) ,
            'DataType' => '2',
        );
        $datas['DataSign'] = $this->encrypt($requestData, static::$AppKey);
        $result=$this->sendPost(static::$ReqURL, $datas);

        //根据公司业务处理返回的信息......

        return $result;
    }


    /**
     *  post提交数据
     * @param  string $url 请求Url
     * @param  array $datas 提交的数据
     * @return url响应返回的html
     */
    public function sendPost($url, $datas) {
        $temps = array();
        foreach ($datas as $key => $value) {
            $temps[] = sprintf('%s=%s', $key, $value);
        }
        $post_data = implode('&', $temps);
        $url_info = parse_url($url);
        if(empty($url_info['port']))
        {
            $url_info['port']=80;
        }
        $httpheader = "POST " . $url_info['path'] . " HTTP/1.0\r\n";
        $httpheader.= "Host:" . $url_info['host'] . "\r\n";
        $httpheader.= "Content-Type:application/x-www-form-urlencoded\r\n";
        $httpheader.= "Content-Length:" . strlen($post_data) . "\r\n";
        $httpheader.= "Connection:close\r\n\r\n";
        $httpheader.= $post_data;
        $fd = fsockopen($url_info['host'], $url_info['port']);
        fwrite($fd, $httpheader);
        $gets = "";
        $headerFlag = true;
        while (!feof($fd)) {
            if (($header = @fgets($fd)) && ($header == "\r\n" || $header == "\n")) {
                break;
            }
        }
        while (!feof($fd)) {
            $gets.= fread($fd, 128);
        }
        fclose($fd);

        return $gets;
    }

    /**
     * 电商Sign签名生成
     * @param data 内容
     * @param appkey Appkey
     * @return DataSign签名
     */
    public function encrypt($data, $appkey) {
        return urlencode(base64_encode(md5($data.$appkey)));
    }
    /**************************************************************
     *
     *  使用特定function对数组中所有元素做处理
     *  @param  string  &$array     要处理的字符串
     *  @param  string  $function   要执行的函数
     *  @return boolean $apply_to_keys_also     是否也应用到key上
     *  @access public
     *
     *************************************************************/
    public function arrayRecursive(&$array, $function, $apply_to_keys_also = false)
    {
        static $recursive_counter = 0;
        if (++$recursive_counter > 1000) {
            die('possible deep recursion attack');
        }
        foreach ($array as $key => $value) {
            if (is_array($value)) {
                $this->arrayRecursive($array[$key], $function, $apply_to_keys_also);
            } else {
                $array[$key] = $function($value);
            }

            if ($apply_to_keys_also && is_string($key)) {
                $new_key = $function($key);
                if ($new_key != $key) {
                    $array[$new_key] = $array[$key];
                    unset($array[$key]);
                }
            }
        }
        $recursive_counter--;
    }


    /**************************************************************
     *
     *  将数组转换为JSON字符串（兼容中文）
     *  @param  array   $array      要转换的数组
     *  @return string      转换得到的json字符串
     *  @access public
     *
     *************************************************************/
    public function JSON($array) {
        $this->arrayRecursive($array, 'urlencode', true);
        $json = json_encode($array);
        return urldecode($json);
    }
}
?>